package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     * @param request
     * @return
     */
    @Override
    public R<String> sendMsg(User user, HttpServletRequest request) {
        //生成一个验证码
        //String code = ValidateCodeUtils.generateValidateCode(6) + " ";

        //smsUtil 发送短信
//        boolean result = SMSUtils.sendMessage(user.getPhone(), code);
//
//        if (!result){
//            return R.error("验证码发送失败");
//        }

       /* String code = "123456";
        //把验证码存储起来
       // request.getSession().setAttribute(user.getPhone(),code);
        */
        //获取手机号
        String phone=user.getPhone ();
       /* Long count=redisTemplate.opsForValue ().increment (user.getPhone (), 1);
        if(count==1){
            //设置过期时间
            redisTemplate.expire (user.getPhone (),1, TimeUnit.SECONDS);
        }else if(count>2){
            return R.error ("不要重复点击");
        }*/
        Boolean flag=redisTemplate.hasKey (phone);
        if (flag) {
            return R.error ("验证码在有效期内，勿重复点击");
        }
        /*String code1 = (String) redisTemplate.opsForValue().get("code");
        if (code1!=null){
            return R.error("短信还未过期");
        }*/
        if (StringUtils.isNotEmpty (phone)) {
            //生成随机的4位验证码
            String code=ValidateCodeUtils.generateValidateCode (4).toString ();
            log.info ("code={}", code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //需要将生成的验证码保存到Session
            //session.setAttribute(phone,code);

            //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue ().set (phone, code, 5l, TimeUnit.MINUTES);
            //redisTemplate.opsForValue ().set ("code", code, 100, TimeUnit.SECONDS);
            return  R.success ("短信发送成功");
        }
        return R.error ("短信发送失败");
    }

    /**
     * 登陆验证
     * @param map
     * @param request
     * @return
     */
    @Override
    public R<User> login(Map map, HttpServletRequest request) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        log.info(code);

        //Object codeInSession = request.getSession().getAttribute(phone);
        //从redis中获取缓存
        Object codeInSession= redisTemplate.opsForValue ().get (phone);
        if (codeInSession != null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<>();
            lwq.eq(User::getPhone,phone);

            User user = userMapper.selectOne(lwq);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userMapper.insert(user);
            }
            request.getSession().setAttribute("user", user.getId());
           ////从Redis中删除缓存的验证码
            redisTemplate.delete (phone);
            return R.success(user);
        }
        return null;
    }
}
